import logging
import unittest

import requests
from parameterized import parameterized

from api.approve_api import ApproveApi
from api.login_api import LoginApi
from api.recharge_api import RechargeApi
from utils import read_html, read_data, common_assert


class TestApproveApi(unittest.TestCase):
    def setUp(self):
        self.session = requests.Session()
        logging.info(F"创建session对象地址{self.session}")
        self.client = RechargeApi(self.session)
        LoginApi(self.session).login_api()

    def tearDown(self):
        self.session.close()
        logging.info(F"session对象{self.session}被关闭")

    @parameterized.expand(read_data("register_data.json", "captcha_code_api"))
    def test01_captcha_code_api(self, random, expect_code):
        try:
            resp = self.client.captcha_code_api(random)
            logging.info(f"预期响应状态码结果: {expect_code} / 实际响应状态码结果: {resp.status_code}")
            self.assertEqual(expect_code, resp.status_code)
            logging.info("断言通过")
        except Exception as e:
            logging.error(f"断言失败: {e}")
            raise

    @parameterized.expand(read_data("approve_trust_data.json", "recharge_api"))
    def test02_recharge_api(self, payment_type, amount, form_str, vali_code, expect_recharge,
                            expect_tripartite_recharge):
        try:
            self.client.captcha_code_api("0.123")
            resp = self.client.recharge_api(amount, vali_code, payment_type, form_str)
            logging.info(f"响应结果: {resp.text}")
            common_assert(self, resp, expect_recharge)
            # 三方充值
            if resp.json()["status"] == 200:
                key_value = read_html(resp.json()["description"]["form"], "html.parser", "input")
                resp = self.client.tripartite_recharge_api(key_value[0], key_value[1])
                logging.info(f"响应结果: {resp.text}")
                self.assertEqual(200, resp.status_code)
                self.assertIn(expect_tripartite_recharge, resp.text)
                logging.info("断言通过")

        except Exception as e:
            logging.error(f"断言失败: {e}")
            raise
